<script setup lang="ts">
import { ref, reactive, computed } from 'vue'
import { balanceRecordApi, myAccountApi, userClosingApplyLooseApi, rechargeRecordApi } from '~/server/userApi'
import feedback from '~/utils/feedback'
import uploadFrom from '~/components/uploadFrom.vue'
import type { FormInstance, FormRules } from 'element-plus'
// 中文本地化（用于日期组件中文显示）
import zhCn from 'element-plus/es/locale/lang/zh-cn'
const tabList = ref([
  {
    name: '账户充值',
    type: 'accountRecharge',
  },
  {
    name: '充值记录',
    type: 'rechargeRecord',
  },
  {
    name: '账户流水', // 全部
    type: 'all',
  },
  // {
  //   name: '支出',
  //   type: 'expenditure',
  // },
  // {
  //   name: '充值',
  //   type: 'recharge',
  // },
  // {
  //   name: '收入',
  //   type: 'income',
  // },
])

/**
 * 我的账户余额
 */
const { data: myAccount } = await useAsyncData(async () => myAccountApi())

/**
 * 我的余额列表
 */
import { PageQuery } from '~/types/global'
import { QuestionFilled } from '@element-plus/icons-vue'
const where = reactive<PageQuery>({
  page: 1,
  limit: 10,
  type: 'all',
})
const {
  data: tableData,
  refresh,
  pending: listLoading,
} = await useAsyncData(async () => balanceRecordApi(where), {
  default: () => ({
    list: [],
    total: 0,
  }),
})
// 分页数据
const pageChange = (e: number) => {
  where.page = e
  refresh()
}

const handleChangeTab = async (type: string) => {
  where.type = type
  where.page = 1
  if (type === 'accountRecharge') {
    return
  }
  if (type === 'rechargeRecord') {
    rechargeWhere.page = 1
    await loadRechargeRecords()
    return
  }
  refresh()
}

/**
 * 账户充值表单
 * 表单项：
 *  - 充值金额(必填)
 *  - 充值方式单选(非必填：银行转账/支付宝转账/虚拟充值)
 *  - 转账银行卡账号(必填)
 *  - 转账账户名(必填)
 *  - 转账日期(必填)
 *  - 凭证(必填，上传一张图片)
 */
const formRef = ref<FormInstance>()
const rechargeForm = reactive({
  amount: undefined as number | undefined,
  payType: 'bank',
  bankCardNo: '',
  cardholder: '',
  bankName: '',
  alipayAccount: '',
  transferDate: '',
  voucherList: [] as Array<{ name: string; url: string }>,
})

const rules: FormRules = {
  amount: [
    { required: true, message: '请输入充值金额', trigger: 'blur' },
    {
      validator: (_: any, value: number, callback: any) => {
        if (value === undefined || value === null || value === 0) return callback(new Error('充值金额需大于0'))
        if (value < 0) return callback(new Error('充值金额不能为负数'))
        callback()
      },
      trigger: 'change',
    },
  ],
  alipayAccount: [{ required: true, message: '请输入支付宝账号', trigger: 'blur' }],
  bankName: [{ required: true, message: '请输入银行名称', trigger: 'blur' }],
  bankCardNo: [{ required: true, message: '请输入转账银行卡账号', trigger: 'blur' }],
  cardholder: [{ required: true, message: '请输入转账账户名', trigger: 'blur' }],
  transferDate: [{ required: true, message: '请选择转账日期', trigger: 'change' }],
  voucherList: [
    {
      required: true,
      validator: (_: any, value: any[], callback: any) => {
        if (!value || value.length === 0) return callback(new Error('请上传转账凭证'))
        callback()
      },
      trigger: 'change',
    },
  ],
}

// 上传完成/删除回调
const handleUploadComplete = (res: { fileName: string; url: string }) => {
  // 只保留一张
  rechargeForm.voucherList.splice(0, rechargeForm.voucherList.length)
  rechargeForm.voucherList.push({ name: res.fileName, url: res.url })
}
const handleUploadRemove = (_index: number) => {
  // 删除对应索引图片
  if (_index > -1 && _index < rechargeForm.voucherList.length) {
    rechargeForm.voucherList.splice(_index, 1)
  } else {
    rechargeForm.voucherList.splice(0, rechargeForm.voucherList.length)
  }
}
// 提交
const submitRecharge = async () => {
  if (!formRef.value) return
  await formRef.value.validate(async (valid) => {
    if (!valid) return
    // 组装提交参数
    const rechargeData: any = {
      closingPrice: rechargeForm.amount,
      type: rechargeForm.payType, // 'bank' | 'alipay'
      realName: rechargeForm.transferDate, // 后端暂定字段映射：转账日期
      paymentCode: rechargeForm.voucherList.length > 0 ? rechargeForm.voucherList[0].url : '', // 凭证URL
    }
    if (rechargeForm.payType === 'alipay') {
      rechargeData.alipayAccount = rechargeForm.alipayAccount
    }
    if (rechargeForm.payType === 'bank') {
      rechargeData.bankCardNo = rechargeForm.bankCardNo
      rechargeData.cardholder = rechargeForm.cardholder
      rechargeData.bankName = rechargeForm.bankName
    }
    try {
      await userClosingApplyLooseApi(rechargeData)
      feedback.msgSuccess('提交成功，待后台审核')
      // 提交后清空表单
      rechargeForm.amount = undefined
      rechargeForm.alipayAccount = ''
      rechargeForm.bankName = ''
      rechargeForm.payType = 'bank'
      rechargeForm.bankCardNo = ''
      rechargeForm.cardholder = ''
      rechargeForm.transferDate = ''
      rechargeForm.voucherList = []
    } catch (e) {
      // 后端返回异常时给出提示
      feedback.msgError('提交失败，请稍后重试')
    }
  })
}

/**
 * 充值记录分页相关
 */
const rechargeWhere = reactive<PageQuery>({
  page: 1,
  limit: 10,
})
const rechargeLoading = ref<boolean>(false)
const rechargeTable = reactive<{ list: any[]; total: number }>({ list: [], total: 0 })

const loadRechargeRecords = async () => {
  try {
    rechargeLoading.value = true
    const res: any = await rechargeRecordApi(rechargeWhere)
    // console.log(res)
    const list = res?.reduce((prev,cur)=>prev.list.concat(cur.list),{list:[]})
    rechargeTable.list = list || []
    console.log(rechargeTable.list)
    rechargeTable.total = res?.total || 0
  } finally {
    rechargeLoading.value = false
  }
}

const rechargePageChange = async (p: number) => {
  rechargeWhere.page = p
  await loadRechargeRecords()
}

/**
 * 计算属性：将账户流水数据扁平化为表格数据
 */
const flatTableData = computed(() => {
  if (!tableData.value || !tableData.value.list || tableData.value.list.length === 0) {
    return []
  }
  return tableData.value.list.reduce((prev: any[], cur: any) => {
    if (cur.list && Array.isArray(cur.list)) {
      return prev.concat(cur.list)
    }
    return prev
  }, [])
})
</script>

<template>
  <div class="balance h-100%">
    <!-- <div class="acea-row header">
      <div class="font18 fontColor333 mb-30px">我的余额</div>
    </div>
    <div class="flex mb-40px justify-center">
      <div class="text-center">
        <div class="text-32px fontColor333 fontsweight dinProSemiBold mb-10px">{{ myAccount.nowMoney }}</div>
        <div class="text-14px text-#999">账户余额(元)</div>
      </div>
      <div class="mr-180px ml-180px text-center">
        <div class="text-32px fontColor333 fontsweight dinProSemiBold mb-10px">{{ myAccount.recharge }}</div>
        <div class="text-14px text-#999">累计充值(元)</div>
      </div>
      <div class="text-center">
        <div class="text-32px fontColor333 fontsweight dinProSemiBold mb-10px">{{ myAccount.monetary }}</div>
        <div class="text-14px text-#999">累计消费(元)</div>
      </div>
    </div> -->
    
    <div class="acea-row">
      <div
        v-for="item in tabList"
        :key="item.type"
        class="item acea-row row-center-wrapper text-16px mr-50px text-#666"
        :class="{ on: where.type === item.type }"
        @click="handleChangeTab(item.type)"
      >
        {{ item.name }}
        <el-tooltip
          v-if="item.type === 'income'"
          class="box-item"
          effect="light"
          content="后台管理员添加余额、用户进行余额充值、推广佣金转入余额"
          placement="bottom-start"
        >
          <el-icon color="#CCCCCC" class="ml-4px"><QuestionFilled /></el-icon>
        </el-tooltip>
      </div>
    </div>
    <!-- 账户充值 -->
    <div v-if="where.type === 'accountRecharge'">
      <!-- 使用中文本地化包裹，确保日期选择器中文显示 -->
      <el-config-provider :locale="zhCn">
      <div class="bg-#FAFAFA b-rd-12px px-20px pt-20px mt-30px pb-20px gap-20px flex justify-center items-start">
        <div class="w-500px box-sizing-border-box">
          <el-form ref="formRef" :model="rechargeForm" :rules="rules" label-width="auto" class="w-500px">
            <el-form-item label="账户余额">
              {{ myAccount.nowMoney }}
            </el-form-item>
            <el-form-item label="充值金额" prop="amount">
              <el-input-number v-model="rechargeForm.amount" :min="0.01" :precision="2" :step="100" placeholder="请输入充值金额" />
            </el-form-item>

            <el-form-item label="充值方式" prop="payType">
              <el-radio-group v-model="rechargeForm.payType">
                <el-radio label="bank">银行转账</el-radio>
                <el-radio label="alipay">支付宝转账</el-radio>
                <!-- <el-radio :label="3">虚拟充值</el-radio> -->
              </el-radio-group>
            </el-form-item>

            <el-form-item label="支付宝账号" prop="alipayAccount" v-if="rechargeForm.payType === 'alipay'">
              <el-input v-model="rechargeForm.alipayAccount" placeholder="请输入支付宝账号" clearable />
            </el-form-item>

            <el-form-item label="转账银行卡账号" prop="bankCardNo" v-if="rechargeForm.payType === 'bank'">
              <el-input v-model="rechargeForm.bankCardNo" placeholder="请输入转账银行卡账号" clearable />
            </el-form-item>

            <el-form-item label="银行名称" prop="bankName" v-if="rechargeForm.payType === 'bank'">
              <el-input v-model="rechargeForm.bankName" placeholder="请输入银行名称" clearable />
            </el-form-item>

            <el-form-item label="转账账户名" prop="cardholder" v-if="rechargeForm.payType === 'bank'">
              <el-input v-model="rechargeForm.cardholder" placeholder="请输入转账账户名" clearable />
            </el-form-item>

            <el-form-item label="转账日期" prop="transferDate">
              <el-date-picker
                v-model="rechargeForm.transferDate"
                type="date"
                placeholder="选择日期"
                value-format="YYYY-MM-DD"
                format="YYYY-MM-DD"
              />
            </el-form-item>

            <el-form-item label="凭证" prop="voucherList">
              <uploadFrom
                :isShow="true"
                :limitNum="1"
                :maxlength="1"
                :pictureList="rechargeForm.voucherList"
                @handleComplete="handleUploadComplete"
                @handleRemoveComplete="handleUploadRemove"
              />
            </el-form-item>

            <el-form-item>
              <el-button type="primary" @click="submitRecharge">提交</el-button>
              <el-button @click="() => { formRef?.resetFields(); rechargeForm.voucherList = [] }">重置</el-button>
            </el-form-item>
          </el-form>
        </div>

        <div class="flex-1 shrink-0">
          <div class="w-full" v-if="rechargeForm.payType === 'bank'">
            <div class="text-16px fontColor333 mb-14px">收款账户信息：</div>
            <div class="text-14px text-#000 mb-20px">请您通过网银转账，或者自行到银行进行汇款，汇款账号如下</div>
            <div class="text-14px text-#000 mb-20px">公司名称：货达环宇（衢州）供应链管理有限公司</div>
            <div class="text-14px text-#000 mb-20px">纳税人识别号：91330802MAER86JY6M</div>
            <div class="text-14px text-#000 mb-20px">地址：浙江省衢州市柯城区万田乡下蒋村355号1幢608-1室</div>
            <div class="text-14px text-#000 mb-20px">电话：18515204111</div>
            <div class="text-14px text-#000 mb-20px">账号：201000399205800</div>
            <div class="text-14px text-#000 mb-20px">开户行：浙江衢州柯城农村商业银行股份有限公司荷花支行南区分理处</div>
          </div>
          <div class="w-full" v-if="rechargeForm.payType === 'alipay'">
            <div class="text-16px fontColor333 mb-14px">收款账户信息：</div>
            <div class="text-14px text-#000 mb-20px">企业支付宝收款账户：3434323798@qq.com</div>
            <div class="text-14px text-#000 mb-20px">企业支付宝账户名称：货达环宇（衢州）供应链管理有限公司</div>
          </div>
        </div>
      </div>
      </el-config-provider>
    </div>
    <!-- 充值记录 -->
    <div v-else-if="where.type === 'rechargeRecord'">
      <div v-loading="rechargeLoading" class="bg-#FAFAFA b-rd-12px px-20px pt-20px mt-30px min-h-63%">
        <div v-if="rechargeTable.list.length > 0">
          <div v-for="(item, idx) in rechargeTable.list" :key="idx" class="balance-item borderBotDas py-16px">
            <div class="flex-between-center mb-10px">
              <div class="text-16px fontColor333">结算单号：{{ item.closingNo || '-' }}</div>
              <div class="text-18px dinProSemiBold" :class="'text-#43B36D'">+￥{{ item.closingPrice || 0 }}</div>
            </div>
            <div class="acea-row row-between-wrapper text-14px text-#666 flex-wrap">
              <div class="mr-30px mb-8px">结算类型：{{ item.closingType === 'bank' ? '银行卡' : (item.closingType === 'alipay' ? '支付宝' : (item.closingType || '-')) }}</div>
              <div class="mr-30px mb-8px">转账卡号：{{ item.bankCardNo || '-' }}</div>
              <div class="mr-30px mb-8px">支付宝账号：{{ item.alipayAccount || '-' }}</div>
              <div class="mr-30px mb-8px">审核状态：
                {{ item.auditStatus === 0 ? '待审核' : (item.auditStatus === 1 ? '通过审核' : (item.auditStatus === 2 ? '审核失败' : (item.auditStatus ?? '-'))) }}
              </div>
              <div class="mr-30px mb-8px">转账日期：{{ item.realName || '-' }}</div>
              <div class="mr-30px mb-8px">申请时间：{{ item.createTime || '-' }}</div>
            </div>
          </div>
          <div class="acea-row row-middle mt-30px">
            <el-pagination
              background
              layout="prev, pager, next"
              :total="rechargeTable.total"
              :page-size="rechargeWhere.limit"
              :current-page="rechargeWhere.page"
              @update:current-page="rechargePageChange"
              class="page-item"
            />
          </div>
        </div>
        <div v-else class="w-100%">
          <empty-page title="暂无充值记录~">
            <template #emptyImage>
              <img src="@/assets/images/wuzhangdan.png" />
            </template>
          </empty-page>
        </div>
      </div>
    </div>
    <div v-else v-loading="listLoading">
      <div v-if="tableData.total > 0" class="bg-#FAFAFA b-rd-12px px-20px pt-20px mt-30px min-h-63%">
        <el-table :data="flatTableData" stripe style="width: 100%">
          <el-table-column type="index" label="序号" width="80" :index="(index: number) => index + 1 + ((where.page || 1) - 1) * (where.limit || 10)" />
          
          <el-table-column label="单号" min-width="200">
            <template #default="{ row }">
              <div>{{ row.type == 1 ? '充值单号' : '订单号' }}: {{ row.linkId }}</div>
            </template>
          </el-table-column>
          <el-table-column prop="remark" label="备注" min-width="150" />
          <el-table-column label="金额" min-width="120" align="right">
            <template #default="{ row }">
              <div v-if="row.type == 1" class="text-#43B36D dinProSemiBold text-16px">
                +￥{{ row.amount }}
              </div>
              <div v-else class="font-color dinProSemiBold text-16px">-￥{{ row.amount }}</div>
            </template>
          </el-table-column>
          <el-table-column label="余额" min-width="120" align="right">
            <template #default="{ row }">
              <div class="text-14px">{{ row.balance }}</div>
            </template>
          </el-table-column>
           <el-table-column prop="createTime" label="时间" min-width="180" />
        </el-table>
      </div>
    </div>
    <div v-if="where.type !== 'accountRecharge' && where.type !== 'rechargeRecord'">
      <div v-if="tableData.total > 0" class="acea-row row-middle mt-30px">
        <el-pagination
          background
          layout="prev, pager, next"
          :total="tableData.total"
          :page-size="where.limit"
          :current-page="where.page"
          @update:current-page="pageChange"
          class="page-item"
        />
      </div>
      <div v-else class="w-100%">
        <empty-page title="暂无账单明细呦~">
          <template v-slot:emptyImage>
            <img src="@/assets/images/wuzhangdan.png" />
          </template>
        </empty-page>
      </div>
    </div>
  </div>
</template>

<style scoped lang="scss">
.balance {
  .item {
    position: relative;
    cursor: pointer;
    &.on {
      color: #e93323;
      &::before {
        content: '';
        position: absolute;
        top: 31px;
        bottom: 18px;
        height: 2px;
        width: 22px;
        background: #e93323;
      }
    }
  }
  &-item {
    margin-bottom: 20px;
    &:nth-last-child(1) {
      margin-bottom: 0;
    }
  }
}
</style>
